# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '20171952851G': {  # dwc 支付宝：3.6%（5---3000），d0结算。
        'API_KEY': '08C74FB66198D3CB2C5B4F20D5155DC80B2F6D6D61C7519E',
        'gateway': 'http://shanghu.hxbpay.com:8888/Interface_WAPPaymentment.action',
        'query_gateway': 'http://shanghu.hxbpay.com:8888/Interface_QueryDeal.action',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s = s[0:len(s) - 1]
    s += key
    _LOGGER.info("guangtongpay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("guangtongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 交易类型:
# 微信WAP(wechart_wap),
# 支付宝WAP(alipay_wap),
# QQWAP支付(qq_wap),
# 京东钱包WAP(jd_wap),
# 微信WAP反扫(wechartf_wap),
# 支付宝WAP反扫(alipayf_wap)
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'wechart_wap'
    elif service == 'alipay':
        payType = 'alipay_wap'
    elif service == 'qq':
        payType = 'qq_wap'
    else:
        payType = 'jd_wap'
    return payType


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantNo', app_id),
        ('orderNo', str(pay.id)),
        ('money', '%.2f' % pay_amount),
        ('summary', 'charge'),
        (
        'returnURL', '{}/pay/api/{}/guangtongpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notifyURL', '{}/pay/api/{}/guangtongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('type', _get_pay_type(service)),
        ('appType', 'Wap'),
        ('appName', settings.NOTIFY_PREFIX),
        ('appPackage', settings.NOTIFY_PREFIX),
        ('ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("guangtongpay create: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('guangtongpay create rsp, %s', response.text)
    return {
        'charge_info': json.loads(response.text)['result'].replace('HTTPS://QR.ALIPAY.COM/', 'https://qr.alipay.com/')}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("guangtongpay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("guangtongpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('guangtongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['code'])
    trade_no = data['sysNo']
    total_fee = float(data['money'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 订单状态：0000:成功，0001:失败，0002：处理中
    if trade_status == '0000':
        _LOGGER.info('guangtongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    service = pay_order.service
    if service == 'wechat':
        service = 'wxpay'
    parameter_dict = OrderedDict((
        ('merchantNo', app_id),
        ('orderNo', str(pay_order.id)),
        ('summary', 'charge'),
        ('type', _get_pay_type(service)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('guangtongpay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('guangtongpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['code'])
        total_fee = float(data['money'])
        trade_no = data['sysNo']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 支付状态：0000：成功,0001: 失败，0002: 处理中
        if trade_status == '0000':
            _LOGGER.info('guangtongpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
